<template>
  <div
    class="chat-v2-container"
    :class="{ 'dark-mode': isDarkMode, dark: isDarkMode }"
    :data-theme="isDarkMode ? 'dark' : 'light'"
  >
    <!-- 左侧菜单 -->
    <div class="left-panel glass-effect" :class="{ collapsed: isCollapsed }">
      <!-- 顶部区域 - Logo -->
      <div class="logo-area">
        <img src="@/assets/logo.svg" alt="析语Datatk" class="sidebar-logo" v-if="!isCollapsed" />
        <img src="@/assets/logonotext.svg" alt="析语Datatk" class="logo-small" v-else />
      </div>

      <!-- 中间区域 - 主导航菜单 -->
      <div class="history-menu" v-if="!isCollapsed">
        <div class="history-menu-title">主菜单</div>
        <el-menu
          :default-active="activeMenu"
          class="history-menu-list"
          :collapse="isCollapsed"
          @select="handleMenuSelect"
          :collapse-transition="false"
          style="background-color: transparent; border: none"
        >
          <el-menu-item index="chat" class="history-menu-item" style="padding: 0px">
            <div class="menu-item-content">
              <div class="menu-item-left">
                <el-icon><ChatDotSquare /></el-icon>
                <span>会话</span>
              </div>
            </div>
          </el-menu-item>

          <el-menu-item index="report" class="history-menu-item" style="padding: 0px">
            <div class="menu-item-content">
              <div class="menu-item-left">
                <el-icon><DataAnalysis /></el-icon>
                <span>报告</span>
              </div>
            </div>
          </el-menu-item>
          <el-menu-item index="dataset" class="history-menu-item" style="padding: 0px">
            <div class="menu-item-content">
              <div class="menu-item-left">
                <el-icon><Files /></el-icon>
                <span>数据集</span>
              </div>
            </div>
          </el-menu-item>
          <el-menu-item index="knowledge" class="history-menu-item" style="padding: 0px">
            <div class="menu-item-content">
              <div class="menu-item-left">
                <el-icon><Collection /></el-icon>
                <span>知识库</span>
              </div>
            </div>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 折叠模式下的图标菜单 -->
      <div class="icon-menu" v-if="isCollapsed">
        <el-tooltip content="会话" placement="right" :show-after="300">
          <div
            class="icon-menu-item"
            :class="{ active: activeMenu === 'chat' }"
            @click="handleMenuSelect('chat')"
          >
            <el-icon><ChatDotSquare /></el-icon>
          </div>
        </el-tooltip>
        <el-tooltip content="报告" placement="right" :show-after="300">
          <div
            class="icon-menu-item"
            :class="{ active: activeMenu === 'report' }"
            @click="handleMenuSelect('report')"
          >
            <el-icon><DataAnalysis /></el-icon>
          </div>
        </el-tooltip>
        <el-tooltip content="数据集" placement="right" :show-after="300">
          <div
            class="icon-menu-item"
            :class="{ active: activeMenu === 'dataset' }"
            @click="handleMenuSelect('dataset')"
          >
            <el-icon><Files /></el-icon>
          </div>
        </el-tooltip>
        <el-tooltip content="知识库" placement="right" :show-after="300">
          <div
            class="icon-menu-item"
            :class="{ active: activeMenu === 'knowledge' }"
            @click="handleMenuSelect('knowledge')"
          >
            <el-icon><Collection /></el-icon>
          </div>
        </el-tooltip>


      </div>

      <!-- 底部区域 - 主题切换和用户信息 -->
      <div class="sidebar-footer" v-if="!isCollapsed">
        <div class="left-controls">
          <el-button :icon="Fold" circle @click="toggleCollapse" class="collapse-button" />
          <el-button
            :icon="isDarkMode ? Sunny : Moon"
            circle
            @click="toggleTheme"
            class="theme-button"
          />
        </div>

        <div class="right-controls">
          <el-dropdown trigger="click" @command="handleUserCommand">
            <div class="user-avatar-wrapper">
              <el-avatar :size="36" :src="userInfo.avatar" />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>
                  <div class="user-info">
                    <div class="username">{{ userInfo.username }}</div>
                    <div class="email">{{ userInfo.email }}</div>
                  </div>
                </el-dropdown-item>
                <el-dropdown-item command="plugin-integration">
                  <el-icon><Connection /></el-icon>
                  <span>插件集成</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="settings">
                  <el-icon><Setting /></el-icon>
                  <span>个人设置</span>
                </el-dropdown-item>
                <el-dropdown-item command="logout">
                  <el-icon><Lock /></el-icon>
                  <span>退出系统</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 折叠模式下的底部按钮 -->
      <div class="collapsed-footer" v-if="isCollapsed">
        <el-tooltip content="展开菜单" placement="right">
          <el-button :icon="Expand" circle @click="toggleCollapse" class="collapse-button" />
        </el-tooltip>
        <el-tooltip content="切换主题" placement="right">
          <el-button
            style="margin-left: 0px"
            :icon="isDarkMode ? Sunny : Moon"
            circle
            @click="toggleTheme"
            class="theme-button"
          />
        </el-tooltip>
        <el-dropdown trigger="click" @command="handleUserCommand">
          <el-avatar :size="30" :src="userInfo.avatar" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item disabled>
                <div class="user-info">
                  <div class="username">{{ userInfo.username }}</div>
                  <div class="email">{{ userInfo.email }}</div>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="plugin-integration">
                <el-icon><Connection /></el-icon>
                <span>插件集成</span>
              </el-dropdown-item>
              <el-dropdown-item divided command="settings">
                <el-icon><Setting /></el-icon>
                <span>个人设置</span>
              </el-dropdown-item>
              <el-dropdown-item command="logout">
                <el-icon><Lock /></el-icon>
                <span>退出系统</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content-area">
      <!-- 添加标题栏 -->
      <!-- <div class="content-header">
        <div class="content-title">
          <el-icon class="title-icon">
            <component :is="activeMenuIcon" />
          </el-icon>
          <h2>{{ activeMenuTitle }}</h2>
        </div>
      </div> -->

      <div class="content-main">
        <transition name="fade-switch" mode="out-in">
          <component :is="activeComponent" :isDarkMode="isDarkMode"></component>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, provide, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Moon,
  Sunny,
  Setting,
  Lock,
  Fold,
  Expand,
  ChatDotSquare,
  Files,
  DataAnalysis,
  Collection,
  Connection,
} from '@element-plus/icons-vue'
import { setToken, getUserInfo as getStoredUserInfo } from '../client/api/auth'
import ClientApp from '../client/views/chat.vue'
import DatasetComponent from '../client/views/DatasetComponent.vue'
import ReportComponent from '../client/views/ReportComponent.vue'
import KnowledgeComponent from '../client/views/KnowledgeComponent.vue'
import { useRouter, useRoute } from 'vue-router'

// 折叠状态
const isCollapsed = ref(true)
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 初始化路由
const router = useRouter()
const route = useRoute()

// 从当前路由提取活动菜单
const activeMenu = ref(route.meta.activeMenu || 'chat')

// 用户信息
const userInfo = ref(getStoredUserInfo() || {})

// 主题模式 - 默认为暗黑模式
const isDarkMode = ref(localStorage.getItem('theme') === 'dark' ? true  : false)
provide('isDarkMode', isDarkMode)

// 切换主题模式
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  localStorage.setItem('theme', isDarkMode.value ? 'dark' : 'light')

  // 应用主题
  const htmlEl = document.documentElement
  if (isDarkMode.value) {
    htmlEl.classList.add('dark')
    document.body.setAttribute('class', 'el-dark-mode')
    document.documentElement.style.setProperty('--el-color-primary', '#409EFF')
  } else {
    htmlEl.classList.remove('dark')
    document.body.removeAttribute('class')
    document.documentElement.style.removeProperty('--el-color-primary')
  }
}
// 处理菜单选择 - 修改为使用路由导航
const handleMenuSelect = (index) => {
  router.push(`/chat/${index}`)
}

// 监听路由变化以更新activeMenu
watch(
  () => route.meta.activeMenu,
  (newActiveMenu) => {
    if (newActiveMenu) {
      activeMenu.value = newActiveMenu
    }
  },
)

// 根据当前选中的菜单返回对应的组件
const activeComponent = computed(() => {
  switch (activeMenu.value) {
    case 'chat':
      return ClientApp
    case 'dataset':
      return DatasetComponent
    case 'report':
      return ReportComponent
    case 'knowledge':
      return KnowledgeComponent
    default:
      return ClientApp
  }
})

// 处理用户下拉菜单命令
const handleUserCommand = (command) => {
  switch (command) {
    case 'plugin-integration':
      // 在新窗口打开插件集成页面
      window.open('/ai-assistant-demo-v2.html', '_blank')
      break
    case 'settings':
      ElMessage.info('个人设置功能即将上线')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 清除token
      setToken('')
      // 清除localStorage中的用户信息
      localStorage.removeItem('username')
      ElMessage.success('已退出系统')
      // 客户端退出，跳转到登录页
      window.location.href = '/login'
    })
    .catch(() => {})
}

// 在组件挂载时从路由中设置正确的活动菜单
onMounted(() => {
  // 从路由中获取活动菜单
  if (route.meta.activeMenu) {
    activeMenu.value = route.meta.activeMenu
  } else {
    // 如果路由没有指定activeMenu，根据路径判断
    const path = route.path
    if (path.includes('/dataset')) {
      activeMenu.value = 'dataset'
    } else if (path.includes('/report')) {
      activeMenu.value = 'report'
    } else if (path.includes('/knowledge')) {
      activeMenu.value = 'knowledge'
    } else {
      activeMenu.value = 'chat'
    }
  }

  // 从本地存储读取主题设置
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    isDarkMode.value = savedTheme === 'dark'
  } else {
    // 默认使用暗色主题
    isDarkMode.value = false
    localStorage.setItem('theme', 'light')
  }

  // 应用主题
  const htmlEl = document.documentElement
  if (isDarkMode.value) {
    htmlEl.classList.add('dark')
    document.body.setAttribute('class', 'el-dark-mode')
    document.documentElement.style.setProperty('--el-color-primary', '#409EFF')
  } else {
    htmlEl.classList.remove('dark')
    document.body.removeAttribute('class')
    document.documentElement.style.removeProperty('--el-color-primary')
  }
})
</script>

<style scoped>
.chat-v2-container {
  display: flex;
  height: 100vh;
  width: 100%;
  border: 0;
  background-color: var(--app-bg-color, #f5f7fa);
  color: var(--app-text-primary, #303133);
  overflow: hidden;
}

/* 左侧菜单样式 */
.left-panel {
  width: 220px;
  flex-shrink: 0;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
  border-radius: 0;
  margin: 0;
  padding: 0;
  box-shadow: var(--app-shadow-hover);
}

.left-panel.collapsed {
  width: 64px;
}

.left-panel.collapsed .sidebar-logo {
  display: none;
}

/* Logo区域样式 */
.logo-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  height: 60px;
  box-shadow: var(--app-shadow-hover);
}

.left-panel.collapsed .logo-area {
  justify-content: center;
  padding: 10px 0;
  height: 60px;
}

.sidebar-logo {
  height: 55px;
  width: auto;
}

.logo-small {
  height: 60px;
  width: auto;
  margin-top: 10px;
}

/* 历史菜单标题样式 */
.history-menu-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--app-text-primary, #303133);
  padding: 15px 15px 10px;
  text-align: left;
}

.history-menu {
  flex: 1;
  overflow-y: auto;
  padding: 0px 10px 10px;
}

.history-menu-list {
  width: 100%;
}

/* 菜单项样式 */
.history-menu-item {
  border-radius: 4px;
  margin-bottom: 6px;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  border: 1px solid transparent;
}

.history-menu-item::after {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border-radius: 6px;
  background: transparent;
  border: 2px solid transparent;
  pointer-events: none;
  transition: all 0.25s ease-in-out;
  z-index: -1;
}

.history-menu-item:hover {
  border-color: #e4e7ed;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
  transform: translateY(-1px);
}

.history-menu-item:hover::after {
  border-color: rgba(64, 158, 255, 0.2);
  box-shadow: 0 0 8px 1px rgba(64, 158, 255, 0.1);
}

.el-menu-item.is-active {
  background-color: rgba(64, 158, 255, 0.1) !important;
  border-color: rgba(64, 158, 255, 0.2);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.05);
}

.menu-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 10px 12px;
  transition: all 0.3s;
}

.menu-item-left {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: calc(100% - 40px);
}

.menu-item-left span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 折叠模式下的图标菜单 */
.icon-menu {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  flex: 1;
}

.icon-menu-item {
  font-size: 20px;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.3s;
  color: #606266;
}

.icon-menu-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.icon-menu-item.active {
  background-color: #409eff;
  color: white;
}

/* 底部区域 */
.sidebar-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.left-controls {
  display: flex;
  gap: 8px;
}

.right-controls {
  display: flex;
}

.theme-button,
.collapse-button {
  width: 36px;
  height: 36px;
}

.user-avatar-wrapper {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.user-avatar-wrapper:hover {
  transform: scale(1.1);
}

.collapsed-footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 10px 0;
}

.user-info {
  padding: 4px 0;
}

.username {
  font-weight: 500;
}

.email {
  font-size: 12px;
  color: #909399;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 内容区域标题栏 */
.content-header {
  padding: 0 24px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.content-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.content-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--app-text-primary, #303133);
}

.title-icon {
  font-size: 22px;
  color: #409eff;
}

/* 内容主区域 */

/* 深色模式样式 */

.dark-mode .history-menu-title {
  color: #e0e0e0;
}

.dark-mode .collapse-button,
.dark-mode .theme-button {
  color: #a6a6a6;
}

.dark-mode .history-menu-item {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border-color: rgba(60, 60, 60, 0.2);
}

.dark-mode .history-menu-item:hover {
  border-color: rgba(80, 80, 80, 0.3);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  background-color: rgba(45, 45, 45, 0.7);
}

.dark-mode .history-menu-item:hover::after {
  border-color: rgba(64, 158, 255, 0.3);
}

.dark-mode .el-menu-item.is-active {
  background-color: rgba(64, 158, 255, 0.2) !important;
}

.dark-mode .menu-item-left {
  color: #e0e0e0;
}

.dark-mode .icon-menu-item {
  color: #a6a6a6;
}

.dark-mode .icon-menu-item:hover {
  background-color: rgba(64, 158, 255, 0.2);
  color: #409eff;
}

.dark-mode .username {
  color: #e0e0e0;
}

.dark-mode .email {
  color: #a0a0a0;
}

.dark-mode .content-header {
  background-color: #222;
  border-color: #2a2a2a;
}

.dark-mode .content-title h2 {
  color: #e0e0e0;
}

/* 过渡动画 */
.fade-switch-enter-active,
.fade-switch-leave-active {
  transition: opacity 0.3s ease;
}

.fade-switch-enter-from,
.fade-switch-leave-to {
  opacity: 0;
}
</style>
